import 'dart:convert';

import 'package:confetti/confetti.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:hive/hive.dart';
import 'package:ichinesereader/constants.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/exam/ExamQuestionIndexPage.dart';
import 'package:ichinesereader/exam/dto/assessment.response.dart';
import 'package:ichinesereader/exam/dto/assessment_question_record.body.dart';
import 'package:ichinesereader/service/assessment.dart';
import 'package:ichinesereader/utils/log.dart';

class PlaceController extends GetxController {
  RxInt stepTop = 0.obs;
  List stepTwoAnswerList = ['B', 'B', 'B', 'B'];
  RxInt bottomBtnStatus = 0.obs; // 0:hide   next 1:2 submit 3:4
  RxString stepTwoText = 'Simplified'.obs;
  RxString stepTwoAudio = 'Mandarin'.obs;

  final AssessmentServiceProvider _service = AssessmentServiceProvider();
  QuestionPart? dataPart;
  List<String>? saveAnswer = [];
  Rx<int> currentQuestionStepIndex = 0.obs;

  Rx<UiQuestionStepTopic> currentQuestionStepTopic = UiQuestionStepTopic().obs;
  Rx<UiQuestionStepBody> currentQuestionStepBody = UiQuestionStepBody().obs;
  List<UiQuestionStep> questionStepList = [];
  List<UiPartIndex> partIndexList = [];
  String username = '';
  String levelRange = '';
  String level = '';
  bool isStudent = false;
  ConfettiController controllerCenter =
      ConfettiController(duration: const Duration(seconds: 10));

  UiQuestionStep? currentQuestionStep;

  void nextPage() {
    if (currentQuestionStepIndex.value >= questionStepList.length - 1) return;
    currentQuestionStepIndex.value++;
    _buildQuestionRecordList(currentQuestionStepIndex.value - 1);
    if (currentQuestionStepIndex.value == questionStepList.length - 1) {
      bottomBtnStatus.value = 3;
    } else {
      bottomBtnStatus.value = 1;
    }
    _resetPageInfo();
  }

  void submitAction() {
    _submitReportRecord(currentQuestionStepIndex.value);
  }

  Future<void> _submitReportRecord(int answerPageIndex) async {
    EasyLoading.show();
    try {
      String? dataJson = await _service.postSubmitPlacementRecord({
        "record": _buildQuestionRecordList(answerPageIndex),
        "type": "PRE_TEST",
        "userName": username
      });
      if (dataJson != null) {
        String splitStr = '\"result\":{\"list\":[';
        if (dataJson.contains(splitStr)) {
          var result = QuestionPart.fromJson(json.decode(dataJson.replaceFirst(
              splitStr, '\"result\":{\"questions\":['))['result']);
          dataPart = result;
          _buildExamUiPartIndex(result);
          _buildQuestionStepList(result);
          _buildInitPageInfo(result);
          bottomBtnStatus.value = 1;
        } else {
          Map result = json.decode(dataJson)['result'];
          levelRange = result['levelRange'].toString();
          level = result['level'].toString();
          stepTop.value = 3;
          bottomBtnStatus.value = 0;
        }
      }
    } catch (e) {
      Log.debug(e);
    } finally {
      EasyLoading.dismiss();
    }
  }

  List<Map> _buildQuestionRecordList(int answerPageIndex) {
    List<Map> questionRecordList = [];
    //Part
    int questionStepIndex = -1;
    // ignore: unused_local_variable
    int questionStepNum = -1;
    var sectionDataList = dataPart!.questions;
    //Section
    for (var sIndex = 0; sIndex < sectionDataList!.length; sIndex++) {
      var sectionData = sectionDataList[sIndex];
      var questionDataList = sectionData.question;
      //Question
      for (var qIndex = 0; qIndex < questionDataList!.length; qIndex++) {
        QuestionItem questionData = questionDataList[qIndex];

        questionStepNum++;
        questionStepIndex++;
        if (answerPageIndex == questionStepIndex &&
            !(saveAnswer == null ||
                saveAnswer!.isEmpty ||
                saveAnswer![0].isEmpty)) {
          dataPart!.questions![sIndex].question![qIndex].answer = saveAnswer;
          questionRecordList.add(QuestionSingleStep(
                  answer: saveAnswer,
                  number: questionData.number,
                  questionId: sectionData.id)
              .toJson());
        } else {
          if (!(questionData.answer == null || questionData.answer!.isEmpty)) {
            questionRecordList.add(QuestionSingleStep(
                    answer: questionData.answer,
                    number: questionData.number,
                    questionId: sectionData.id)
                .toJson());
          }
        }
      }
    }

    return questionRecordList;
  }

  void _resetPageInfo() {
    var oldQuestionStep = currentQuestionStep;
    currentQuestionStep = questionStepList[currentQuestionStepIndex.value];

    QuestionPart? questionPart = dataPart;
    if (currentQuestionStep?.stepType == UiQuestionStep.STEPTYPE_QUESTION) {
      int sectionIndex = currentQuestionStep?.sectionIndex ?? 0;
      QuestionSection? questionSection = questionPart?.questions?[sectionIndex];
      int questionIndex = currentQuestionStep?.questionIndex ?? 0;
      QuestionItem? questionItem = questionSection?.question?[questionIndex];
      UiQuestionStepBody uiQuestionStepBody = UiQuestionStepBody(
          item: QuestionItem.fromRawJson(questionItem!.toRawJson()));

      QuestionContent? questionHead;
      bool isQuestionLevelTopic = true;
      if (questionSection?.content != null &&
          questionSection?.content?.show != null) {
        isQuestionLevelTopic = false;
        QuestionContent? tempQuestionHead = questionSection?.content;
        questionHead = QuestionContent(
            show: tempQuestionHead?.show,
            text: tempQuestionHead?.text,
            audio: tempQuestionHead?.audio,
            image: tempQuestionHead?.image);
      } else {
        isQuestionLevelTopic = true;
        questionHead = questionItem.head;
        uiQuestionStepBody.item?.head = null;
      }
      if (isQuestionLevelTopic ||
          currentQuestionStep?.partIndex != oldQuestionStep?.partIndex ||
          currentQuestionStep?.sectionIndex != oldQuestionStep?.sectionIndex ||
          currentQuestionStep?.sectionIndex == 0) {
        currentQuestionStepTopic.value =
            UiQuestionStepTopic(head: questionHead);
      }
      currentQuestionStepBody.value = uiQuestionStepBody;
    }
  }

  void loadData(Map param) {
    getPlacementQuizzes(param);
  }

  Future<void> getPlacementQuizzes(param) async {
    EasyLoading.show();
    try {
      var result = await _service.getPlacementQuizzes(param);
      dataPart = result;
      _buildExamUiPartIndex(result);
      _buildQuestionStepList(result);
      _buildInitPageInfo(result);
      if (dataPart != null) {
        stepTop.value = 2;
        bottomBtnStatus.value = 1;
      }
    } catch (e) {
      Log.debug(e);
    } finally {
      EasyLoading.dismiss();
    }
  }

  void _buildInitPageInfo(QuestionPart? partData) {
    currentQuestionStepIndex.value = 0;
    currentQuestionStep = questionStepList[currentQuestionStepIndex.value];
    _resetPageInfo();
  }

  void _buildQuestionStepList(QuestionPart? partData) {
    questionStepList.clear();
    //Part
    int questionStepIndex = -1;
    UiPartIndex partIndex = UiPartIndex('0', 'Part ${0 + 1}');

    var sectionDataList = partData!.questions;
    //Section
    for (var sIndex = 0; sIndex < sectionDataList!.length; sIndex++) {
      var sectionData = sectionDataList[sIndex];
      UiSectionIndex sectionIndex =
          UiSectionIndex('$sIndex', 'Q ${sIndex + 1}');
      //有下边的 content 带表 是section 级别的问题， 无content 带表是 question级别的问题
      //sectionData.content

      var questionDataList = sectionData.question;
      //Question
      for (var qIndex = 0; qIndex < questionDataList!.length; qIndex++) {
        //var questionData = questionDataList[qIndex];

        UiQuestionIndex questionIndex = UiQuestionIndex(
            '$qIndex', '${sIndex + 1}.${qIndex + 1}',
            partIndex: 0, sectionIndex: sIndex, questionIndex: qIndex);

        questionStepIndex++;
        questionStepList.add(UiQuestionStep(
            questionStepIndex,
            '${partIndex.name}-${sectionIndex.name}-${questionIndex.name}',
            'question',
            partIndex: 0,
            sectionIndex: sIndex,
            questionIndex: qIndex));
      }
    }
  }

  void _buildExamUiPartIndex(QuestionPart? partData) {
    partIndexList.clear();
    int questionStepIndex = -1;
    UiPartIndex partIndex = UiPartIndex('0', 'Part ${1}');
    partIndex.sectionIndexList = [];
    var sectionDataList = partData!.questions;
    for (var sIndex = 0; sIndex < sectionDataList!.length; sIndex++) {
      var sectionData = sectionDataList[sIndex];
      UiSectionIndex sectionIndex =
          UiSectionIndex('$sIndex', 'Q ${sIndex + 1}');
      sectionIndex.questionIndexList = [];

      var questionDataList = sectionData.question;
      for (var qIndex = 0; qIndex < questionDataList!.length; qIndex++) {
        questionStepIndex++;
        UiQuestionIndex questionIndex = UiQuestionIndex(
            '$qIndex', '${sIndex + 1}.${qIndex + 1}',
            partIndex: 0,
            sectionIndex: sIndex,
            questionIndex: qIndex,
            questionStepIndex: questionStepIndex);
        sectionIndex.questionIndexList!.add(questionIndex);
      }
      partIndex.sectionIndexList!.add(sectionIndex);
    }
    partIndexList.add(partIndex);
  }

  @override
  void onInit() {
    final box = Hive.box('appconfig');
    isStudent = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Student;
    super.onInit();
  }

  @override
  void onClose() {
    controllerCenter.dispose();
    super.onClose();
  }
}
